﻿using Gasgoo.ShareLibrary.Framework.Options;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using SqlSugarDbType = SqlSugar.DbType;

namespace Gasgoo.DataProvider.SqlSugar
{
    public class SugarLoggerContext : SqlSugarClient
    {
        public SugarLoggerContext(string providerName, IServiceProvider provider) : base(new ConnectionConfig
        {
            ConnectionString = provider.GetRequiredService<AdoNetOptions>().GetConnection(),
            DbType = SqlSugarDbType.SqlServer,
            IsAutoCloseConnection = true,
            ConfigureExternalServices = SqlSugarUtils.GetConfigureExternalServices(),
        }, db =>
        {
            //每次上下文都会执行

            //获取IOC对象不要求在一个上下文
            //var log=s.GetService<Log>()

            //获取IOC对象要求在一个上下文
            //var appServive = s.GetService<IHttpContextAccessor>();
            //var log= appServive?.HttpContext?.RequestServices.GetService<Log>();

            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                //Console.WriteLine("OnLogExecuting: " + sql + "\n" + UtilMethods.GetNativeSql(sql, pars) + "\n");
            };
        })
        {
            SqlSugarUtils<SugarLoggerContext>.CheckDatabaseAndStructure(this);
        }

    }
}
